package com.xe.gae;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.xe.ConfigFactory;
import com.xe.core.XEConstants;
import com.xe.core.XEResource;

public class XEConfigFactory implements ConfigFactory{
	DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	Map<String,String> config;
	ServletContext context ;	

	XEResourceManager4GAE rm = new XEResourceManager4GAE();
	
	
	
	
	public ServletContext getContext() {
		return context;
	}

	@Override
	public void setContext(ServletContext context) {
		this.context = context;
	}

	@Override
	public Map<String, String> getConfig() {
		if (config==null){return load();}
		else return config;
	}

	@Override
	public Map<String,String>  put(String name,String value){
			Entity entity = new Entity("ExtremeEngine",name);
			entity.setProperty("name",name);
			entity.setProperty("value", value);
			config.put(name,value);
			datastore.put(entity);
			return config;
	}

	public  Map<String, String>  load(){
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Query q = new Query("ExtremeEngine");
		PreparedQuery pq = datastore.prepare(q);

		for (Entity result : pq.asIterable()) {
			if (config==null) config=new HashMap<String,String>() ;	

			String name  = (String) result.getProperty("name");
			String value = (String) result.getProperty("value");
			config.put(name, value);
		}
		initScripts();//todo:se deberia modelar distinto.
		if (config==null) return init();
		else return config;
	}
	
	public Map<String,String> init(){
		config=new HashMap<String,String>() ;	
		String script = "new com.xe.gae.XEResourceManager4GAE()";
		
		put(XEConstants.XE_GET_RESOURCE_MANAGER_SCRIPT,script);
		put(XEConstants.SERVICE_SCRIPT,"ExtremeEngine/service.groovy");
		
		initScripts();
		return config;
	}

	private void initScripts() {
		String[] files= new String[3];
		files[0]="ExtremeEngine/service.groovy";
		files[1]="ExtremeEngine/saveResource.groovy";
		files[2]="ExtremeEngine/resourceForm.groovy";

		for(String s:files){
			XEResource r= rm.load(s);
			if (r==null) loadFromFile(s);
		}			
		
	}

	private String loadFromFile(String filename) {
		InputStream is = context.getResourceAsStream("/WEB-INF/"+filename);
		String s = getStringFromInputStream(is);
		XEResource r = new XEResource(filename, XEResource.FILE);
		r.setSource(s);
		rm.save(r);
		return s;
	}
	
	
	private static String getStringFromInputStream(InputStream is) {
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		String line;
		try {
			br = new BufferedReader(new InputStreamReader(is));
			while ((line = br.readLine()) != null) {
				sb.append(line);
				sb.append(System.getProperty("line.separator"));
			}
 
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}
	
}